#include "gane_app.h"
#include "ResourceManager.h"
#include "time.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_render.h>
#include <spdlog/spdlog.h>
#include "Renderer.h"
#include "Camera.h"

using namespace engine::core;
using namespace engine::resource;

engine::core::GaneApp::GaneApp()  : m_isRunning(false)  
{  
    
}

engine::core::GaneApp::~GaneApp()
{
    if (m_isRunning)
    {
        close();
        spdlog::info("GameApp 被销毁时没有显式关闭 现在关闭");
    }
}

void engine::core::GaneApp::run()
{
    if (!init())
    {
        spdlog::error("GameApp 初始化失败");
        return;
    }
	testResourceManager();
    m_time->setTargetFPS(144);
    while (m_isRunning)
    {
		m_time->update(); // 更新时间
		float delta_time = m_time->getDeltaTime(); // 获取上一帧的时间差
        handleEvents();
        update(delta_time); // 假设每帧 16ms
        render();
		spdlog::info("当前帧时间: {} ms", delta_time); // 输出当前帧时间
    }
    close();
    spdlog::info("GameApp 运行结束");
}

void engine::core::GaneApp::testResourceManager()
{
	m_resourceManager->getTexture("F:\\visual studio source\\SunnyLand\\assets\\textures\\Actors\\eagle-attack.png");
	m_resourceManager->getFont("F:\\visual studio source\\SunnyLand\\assets\\fonts\\VonwaonBitmap-16px.ttf", 16);
	m_resourceManager->getSound("F:\\visual studio source\\SunnyLand\\assets\\audio\\button_click.wav");

    //m_resourceManager->unloadTexture("F:\\visual studio source\\SunnyLand\\assets\\textures\\Actors\\eagle-attack.png");
	//m_resourceManager->unloadFont("F:\\visual studio source\\SunnyLand\\assets\\fonts\\VonwaonBitmap-16px.ttf", 16);
	//m_resourceManager->unloadSound("F:\\visual studio source\\SunnyLand\\assets\\audio\\button_click.wav");
}

void engine::core::GaneApp::testRenderer()
{
	engine::render::Sprite sprite_world("F:\\visual studio source\\SunnyLand\\assets\\textures\\Actors\\frog.png");
	engine::render::Sprite sprite_ui("F:\\visual studio source\\SunnyLand\\assets\\textures\\UI\\buttons\\Start1.png");
    engine::render::Sprite sprite_parallax("F:\\visual studio source\\SunnyLand\\assets\\textures\\Layers\\back.png");

	static float rotation = 0.0f;
	rotation += 0.1f;
	glm::vec2 scroll_factor = { 0.5f, 0.5f };
	m_renderer->drawParallax(*m_camera, sprite_parallax, glm::vec2(100,100), scroll_factor, {true,false}, {1.0f,1.0f});
	m_renderer->drawSprite(*m_camera, sprite_world, glm::vec2(200, 200), glm::vec2(1.0f, 1.0f), rotation);
	m_renderer->drawUISprite(sprite_ui, glm::vec2(50, 50), glm::vec2(200, 80));
}

void engine::core::GaneApp::testCamera()
{
    auto keyState = SDL_GetKeyboardState(nullptr);
    const float step = 1.0f; // 每帧移动 1 像素
    if (keyState[SDL_SCANCODE_UP])    m_camera->move(glm::vec2(0.0f, -step));
    if (keyState[SDL_SCANCODE_DOWN])  m_camera->move(glm::vec2(0.0f, step));
    if (keyState[SDL_SCANCODE_LEFT])  m_camera->move(glm::vec2(-step, 0.0f));
    if (keyState[SDL_SCANCODE_RIGHT]) m_camera->move(glm::vec2(step, 0.0f));
}

bool engine::core::GaneApp::init()
{
	spdlog::info("初始化 GameApp");
    if (!initSDL()) return false;
    if (!initTime()) return false;
    if (!initResourceManager()) return false;
	if (!initRenderer()) return false;
	if (!initCamera()) return false;
    m_isRunning = true;
    spdlog::info("GameApp 初始化成功");
    return true;
}

void engine::core::GaneApp::handleEvents()
{
    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_QUIT)
        {
            m_isRunning = false;
            spdlog::info("接收到退出事件，停止运行");
        }
    }
}

void engine::core::GaneApp::update(float delta_time)
{
	testCamera();
}

void engine::core::GaneApp::render()
{
	m_renderer->clearScreen();
	testRenderer();
	m_renderer->present();
    //SDL_RenderClear(sdl_renderer);

    // 渲染操作
    //SDL_RenderPresent(sdl_renderer);
}

void engine::core::GaneApp::close()
{
    if (sdl_renderer)
    {
        SDL_DestroyRenderer(sdl_renderer);
    }
    if (sdl_window)
    {
        SDL_DestroyWindow(sdl_window);
    }
    SDL_Quit();
    m_isRunning = false;
    spdlog::info("GameApp 资源已释放，SDL 已退出");
}

bool engine::core::GaneApp::initSDL()
{
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        spdlog::error("SDL 初始化失败: {}", SDL_GetError());
        return false;
    }

    sdl_window = SDL_CreateWindow("GaneApp", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_BORDERLESS);
    if (!sdl_window)
    {
        spdlog::error("创建 SDL 窗口失败: {}", SDL_GetError());
        return false;
    }

    sdl_renderer = SDL_CreateRenderer(sdl_window, -1, SDL_RENDERER_ACCELERATED);
    if (!sdl_renderer)
    {
        spdlog::error("创建 SDL 渲染器失败: {}", SDL_GetError());
        return false;
    }
    SDL_RenderSetLogicalSize(sdl_renderer, 640, 360);
    spdlog::info("SDL 初始化成功");
	return true;
}

bool engine::core::GaneApp::initTime()
{
    try
    {
        m_time = std::make_unique<Time>();
    }
    catch (const std::exception& e)
    {
		spdlog::error("Time 初始化失败:{}",e.what());
        return false;
    }
	spdlog::info("Time 初始化成功");
    return true;
}

bool engine::core::GaneApp::initResourceManager()
{
    try
    {
		m_resourceManager = std::make_unique<engine::resource::ResourceManager>(sdl_renderer);
    }
    catch (const std::exception& e)
    {
		spdlog::error("ResourceManager 初始化失败:{}", e.what());
		return false;
    }
	spdlog::info("ResourceManager 初始化成功");
	return true;
}

bool engine::core::GaneApp::initRenderer()
{
    try
    {
		m_renderer = std::make_unique<engine::render::Renderer>(sdl_renderer, m_resourceManager.get());
    }
    catch (const std::exception& e)
    {
		spdlog::error("Renderer 初始化失败:{}", e.what());
		return false;
    }
	spdlog::info("Renderer 初始化成功");
	return true;
}

bool engine::core::GaneApp::initCamera()
{
    try
    {
        m_camera = std::make_unique<engine::render::Camera>(glm::vec2(640, 360));
        m_camera->setPosition({ 0.0f,0.0f });
    }
    catch (const std::exception& e)
    {
        spdlog::error("Camera 初始化失败:{}", e.what());
        return false;
    }
    spdlog::info("Camera 初始化成功");
	return true;
}
